package com.ewhale.feitengguest.ui.user.task;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.ewhale.feitengguest.R;
import com.ewhale.feitengguest.dto.TabEntity;
import com.ewhale.feitengguest.dto.TaskCommentDto;
import com.ewhale.feitengguest.dto.TaskDetailsDto;
import com.ewhale.feitengguest.presenter.user.task.TaskDetailsPresenter;
import com.ewhale.feitengguest.ui.WebViewActivity;
import com.ewhale.feitengguest.ui.auth.LoginActivity;
import com.ewhale.feitengguest.ui.user.mine.MyTaskDetailActivity;
import com.ewhale.feitengguest.ui.user.task.adapter.CommentAdapter;
import com.ewhale.feitengguest.ui.user.task.adapter.StepListAdapter;
import com.ewhale.feitengguest.utils.GlideImageLoader;
import com.ewhale.feitengguest.view.user.task.TaskDetailsView;
import com.ewhale.feitengguest.widget.BannerLayout;
import com.ewhale.feitengguest.widget.ShareDialog;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.orhanobut.hawk.Hawk;
import com.simga.library.activity.MBaseActivity;
import com.simga.library.utils.CheckUtil;
import com.simga.library.utils.DateUtil;
import com.simga.library.utils.HawkKey;
import com.simga.library.utils.StringUtil;
import com.simga.library.utils.glide.GlideUtil;
import com.simga.library.widget.BGButton;
import com.simga.library.widget.CoustomRefreshView;
import com.simga.library.widget.HintDialog;
import com.youth.xframe.widget.loadingview.XLoadingView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cc.shinichi.library.ImagePreview;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.wechat.WechatMoments;

public class TaskDetailsActivity extends MBaseActivity<TaskDetailsPresenter> implements TaskDetailsView {
    @BindView(R.id.bannerlayout)
    BannerLayout bannerlayout;
    @BindView(R.id.tv_content_title)
    TextView tvTitle;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_time_hint)
    TextView tvTimeHint;
    @BindView(R.id.tv_times)
    TextView tvTimes;
    @BindView(R.id.tv_over_hint)
    TextView tvOverHint;
    @BindView(R.id.tv_over)
    TextView tvOver;
    @BindView(R.id.listview)
    RecyclerView listview;
    @BindView(R.id.tv_handle)
    TextView tvHandle;
    @BindView(R.id.tv_over_time)
    TextView tvOverTime;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.ref_layout)
    CoustomRefreshView mRefLayout;
    @BindView(R.id.tv_cate)
    TextView mTvCate;
    @BindView(R.id.tv_authTime)
    TextView mTvAuthTime;
    @BindView(R.id.tv_device)
    TextView mTvDevice;
    @BindView(R.id.ll_handle)
    LinearLayout mLlHandle;
    @BindView(R.id.iv_taskQRCode)
    ImageView mIvTaskQRCode;
    @BindView(R.id.tv_linkText)
    TextView mTvLinkText;
    @BindView(R.id.ll_qrCode)
    LinearLayout mLlQrCode;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_right)
    ImageView mIvRight;
    @BindView(R.id.rl_title)
    ConstraintLayout mRlTitleBar;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.topMainTab)
    CommonTabLayout topMainTab;
    @BindView(R.id.btn_cancel)
    BGButton mBtnCancel;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.xloading_view)
    XLoadingView xloadingView;

    private List<TaskDetailsDto.MissionStepDtosBean> stepList = new ArrayList<>();
    private List<String> imageUrl = new ArrayList<>();
    private List<TaskCommentDto> mCommentList = new ArrayList<>();
    private int pageNum = 1;
    private StepListAdapter mStepAdapter;
    private CommentAdapter mCommentAdapter;
    private long missionId;
    private TaskDetailsDto mDetailsDto;
    private MyTime mMyTime;
    private HintDialog mHintDialog;
    private ShareDialog mShareDialog;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();


    public static void open(MBaseActivity mContext, long missionId) {
        Bundle bundle = new Bundle();
        bundle.putLong("missionId", missionId);
        mContext.startActivity(bundle, TaskDetailsActivity.class);
    }

    @Override
    protected void onGetBundle(Bundle bundle) {
        missionId = bundle.getLong("missionId");
    }

    @Override
    protected int getViewId() {
        return R.layout.activity_task_details;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mTabEntities.add(new TabEntity("任务步骤", 0, 0));
        mTabEntities.add(new TabEntity("留言", 0, 0));
        topMainTab.setTabData(mTabEntities);

        mTvTitle.setText("任务详情");
        mTvTitle.setTextColor(Color.WHITE);
        mTvTitle.setVisibility(View.INVISIBLE);
        line.setVisibility(View.INVISIBLE);
        mIvRight.setVisibility(View.VISIBLE);
        mIvRight.setImageResource(R.mipmap.b_nav_icon_share);
        ivBack.setImageResource(R.mipmap.d2_nav_icon_back_white);
        mRlTitleBar.setBackgroundColor(ContextCompat.getColor(mContext, R.color.transparent));
        mRefLayout.setEnableRefresh(false);
        mRefLayout.setEnableLoadmore(false);
        listview.setNestedScrollingEnabled(false);
        bannerlayout.setImageLoader(new GlideImageLoader());
        listview.setLayoutManager(new LinearLayoutManager(mContext));
        listview.setHasFixedSize(true);

        mCommentAdapter = new CommentAdapter(mCommentList,CommentAdapter.USER_SIDE);
        mStepAdapter = new StepListAdapter(stepList);
        listview.setAdapter(mStepAdapter);

        xloadingView.showContent();
        presenter.loadTaskDetail(missionId);
        presenter.loadComment(missionId, pageNum);
    }

    @Override
    protected boolean isUseBaseTitleBar() {
        return false;
    }

    @Override
    protected void initListener() {
        topMainTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (position == 0) {
                    xloadingView.showContent();
                    if (!CheckUtil.isNull(mDetailsDto.getMissionQrcode())) {
                        mIvTaskQRCode.setVisibility(View.VISIBLE);
                    }
                    if (!CheckUtil.isNull(mDetailsDto.getMissionUrl())) {
                        mTvLinkText.setVisibility(View.VISIBLE);
                    }
                    if (!CheckUtil.isNull(mDetailsDto.getMissionUrl()) || !CheckUtil.isNull(mDetailsDto.getMissionQrcode())) {
                        mLlQrCode.setVisibility(View.VISIBLE);
                    }
                    mRefLayout.setEnableLoadmore(false);
                    if (mDetailsDto.getStatus() == -1 || mDetailsDto.getStatus() == 4) {
                        tvHandle.setText("接任务");
                        tvOverTime.setVisibility(View.VISIBLE);
                        mBtnCancel.setVisibility(View.GONE);
                    } else if (mDetailsDto.getStatus() == 0) {
                        mBtnCancel.setVisibility(View.VISIBLE);
                        tvHandle.setText("去提交审核");
                    } else if (mDetailsDto.getStatus() == 1) {
                        mBtnCancel.setVisibility(View.GONE);
                        tvHandle.setText("任务审核中");
                    } else if (mDetailsDto.getStatus() == 2) {
                        mBtnCancel.setVisibility(View.GONE);
                        tvHandle.setText("任务审核失败");
                    } else if (mDetailsDto.getStatus() == 3) {
                        mBtnCancel.setVisibility(View.GONE);
                        tvHandle.setText("任务已完成");
                    }
                    tvOverTime.setVisibility(View.VISIBLE);
                    listview.setAdapter(mStepAdapter);
                } else if (position == 1) {
                    if (mCommentList.size() == 0) {
                        xloadingView.showEmpty();
                    } else {
                        xloadingView.showContent();
                    }
                    mBtnCancel.setVisibility(View.GONE);
                    mLlQrCode.setVisibility(View.GONE);
                    mIvTaskQRCode.setVisibility(View.GONE);
                    mTvLinkText.setVisibility(View.GONE);
                    mRefLayout.setEnableLoadmore(true);
                    tvHandle.setText("去留言");
                    listview.setAdapter(mCommentAdapter);
                    tvOverTime.setVisibility(View.GONE);
                }
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY <= 0) {
                    mRlTitleBar.setBackgroundColor(Color.argb((int) 0, 250, 192, 52));
                    mTvTitle.setVisibility(View.INVISIBLE);
                } else if (scrollY > 0 && scrollY <= mRlTitleBar.getHeight()) {
                    mTvTitle.setVisibility(View.VISIBLE);
                    float scale = (float) scrollY / mRlTitleBar.getHeight();
                    float alpha = (255 * scale);
                    // 只是layout背景透明(仿知乎滑动效果)
                    mRlTitleBar.setBackgroundColor(Color.argb((int) alpha, 250, 192, 52));
                } else {
                    mTvTitle.setVisibility(View.VISIBLE);
                    mRlTitleBar.setBackgroundColor(Color.argb((int) 255, 250, 192, 52));
                }
            }
        });
        mRefLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                pageNum++;
                presenter.loadComment(missionId, pageNum);
            }
        });
        mIvTaskQRCode.setOnClickListener(v -> {
            if (CheckUtil.isNull(mDetailsDto.getMissionQrcode())) return;
            ImagePreview.getInstance().setContext(mContext)
                    .setShowDownButton(true)
                    .setImage(mDetailsDto.getMissionQrcode())
                    .setLoadStrategy(ImagePreview.LoadStrategy.AlwaysOrigin)
                    .setZoomTransitionDuration(300)
                    .setEnableDragClose(true)
                    .setErrorPlaceHolder(R.drawable.default_image).start();
        });
        mStepAdapter.setListener(content -> {
            if(copy(content)){
                showToast("内容已复制到剪切板");
            }
        });
    }

    @Override
    public void showProLoading() {
        showLoading();
    }

    @Override
    public void dimissProLoading() {
        dismissLoading();
    }

    @Override
    public void showErrorMessage(int postCode, String code, String message) {
        showErrorMsg(code, message);
        onLoad(-1);
    }


    @OnClick({R.id.ll_handle, R.id.tv_linkText, R.id.iv_back,
            R.id.iv_right, R.id.btn_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_right:
                mShareDialog = new ShareDialog(mContext);
                mShareDialog.setOnItemClickListener(new ShareDialog.onItemClickListener() {
                    @Override
                    public void onClick(int type) {
                        ShareParams shareParams = new ShareParams();
                        if (type == 1) {//QQ
                            shareParams.setShareType(Platform.SHARE_WEBPAGE);
                            shareParams.setTitle(getResources().getString(R.string.app_name));
                            shareParams.setText(mDetailsDto.getTitle());
                            shareParams.setUrl(mDetailsDto.getMissionUrl());
                            shareParams.setImageUrl(mDetailsDto.getImg());
                            JShareInterface.share(QQ.Name, shareParams, mPlatActionListener);
                        } else {//WeChat
                            Glide.with(mContext).asBitmap().load(mDetailsDto.getImg()).into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
                                    shareParams.setShareType(Platform.SHARE_WEBPAGE);
                                    shareParams.setTitle(getResources().getString(R.string.app_name));
                                    shareParams.setText(mDetailsDto.getTitle());
                                    shareParams.setUrl(mDetailsDto.getMissionUrl());
                                    shareParams.setImageData(bitmap);
                                    JShareInterface.share(Wechat.Name, shareParams, mPlatActionListener);
                                }
                            });
                        }
                    }
                });
                mShareDialog.show();
                break;
            case R.id.ll_handle:
                if (!Hawk.get(HawkKey.IS_USER_LOGIN, false)) {
                    showToast("请先登录账号");
                    LoginActivity.open(mContext);
                    return;
                }
                if (topMainTab.getCurrentTab() == 0) {
                    if (mDetailsDto.getStatus() == -1||mDetailsDto.getStatus() == 4) {
                        mHintDialog = new HintDialog(mContext, "提示", "确定要接该任务？", new String[]{"取消", "确定"});
                        mHintDialog.setCallback(new HintDialog.Callback() {
                            @Override
                            public void callback() {
                                presenter.acceptTask(missionId);
                            }

                            @Override
                            public void cancle() {
                            }
                        });
                        mHintDialog.show();
                    } else {
                        MyTaskDetailActivity.open(mContext, missionId);
                    }
                } else {
                    MsgBoardActivity.open(mContext, missionId);
                }
                break;
            case R.id.tv_linkText:
                if (mDetailsDto == null) return;
                WebViewActivity.open(mContext, "任务详情", mDetailsDto.getMissionUrl());
                break;
            case R.id.btn_cancel:
                mHintDialog = new HintDialog(mContext, "提示", "您确定要取消该任务？", new String[]{"取消", "确定"});
                mHintDialog.setCallback(new HintDialog.Callback() {
                    @Override
                    public void callback() {
                        presenter.cancelTask(missionId);
                    }

                    @Override
                    public void cancle() {
                    }
                });
                mHintDialog.show();
                break;
        }
    }

    @Override
    public void showTaskDetails(TaskDetailsDto result) {
        mDetailsDto = result;
        imageUrl.addAll(Arrays.asList(result.getImg().split(",")));
        bannerlayout.setImages(imageUrl);
        bannerlayout.start();
        tvTitle.setText(result.getTitle());
        tvPrice.setText("￥" + StringUtil.to2Decimal(StringUtil.to2Double(result.getUnitPrice())));
        tvTimes.setText(String.valueOf(result.getSurplusNum()));
        tvOver.setText(result.getEndTimeStr());
        mTvCate.setText(result.getClassificationName());
        mTvAuthTime.setText(result.getAuditHour() + "小时内审核");
        if (result.getDeviceType() == 1) {
            mTvDevice.setText("全部");
        } else if (result.getDeviceType() == 2) {
            mTvDevice.setText("IOS");
        } else if (result.getDeviceType() == 3) {
            mTvDevice.setText("Android");
        }
        stepList.addAll(result.getMissionStepDtos());
        mStepAdapter.notifyDataSetChanged();
        if (!CheckUtil.isNull(result.getMissionQrcode())) {
            GlideUtil.loadPicture(result.getMissionQrcode(), mIvTaskQRCode, R.drawable.default_image);
            mIvTaskQRCode.setVisibility(View.VISIBLE);
        } else {
            mIvTaskQRCode.setVisibility(View.GONE);
        }
        if (!CheckUtil.isNull(result.getMissionUrl())) {
            mTvLinkText.setVisibility(View.VISIBLE);
            mTvLinkText.setText(result.getMissionUrl());
        } else {
            mTvLinkText.setVisibility(View.GONE);
        }
        if (!CheckUtil.isNull(mDetailsDto.getMissionUrl()) || !CheckUtil.isNull(mDetailsDto.getMissionQrcode())) {
            mLlQrCode.setVisibility(View.VISIBLE);
        } else {
            mLlQrCode.setVisibility(View.GONE);
        }
        if (result.getStatus() == -1 || result.getStatus() == 4) {
            tvHandle.setText("接任务");
            tvOverTime.setVisibility(View.VISIBLE);
            mBtnCancel.setVisibility(View.GONE);
            long countDown = (result.getEndTimeStamp() * 1000 - new Date().getTime()) / 1000;
            mMyTime = new MyTime(countDown * 1000, 1000);
            mMyTime.start();
        } else if (result.getStatus() == 0) {
            mBtnCancel.setVisibility(View.VISIBLE);
            tvHandle.setText("去提交审核");
        } else if (result.getStatus() == 1) {
            mBtnCancel.setVisibility(View.GONE);
            tvHandle.setText("任务审核中");
        } else if (result.getStatus() == 2) {
            mBtnCancel.setVisibility(View.GONE);
            tvHandle.setText("任务审核失败");
        } else if (result.getStatus() == 3) {
            mBtnCancel.setVisibility(View.GONE);
            tvHandle.setText("任务已完成");
        }
    }

    private class MyTime extends CountDownTimer {
        public MyTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvOverTime.setText("剩" + DateUtil.formatSeconds(millisUntilFinished / 1000));
        }

        @Override
        public void onFinish() {
            tvOverTime.setText("已结束");
        }
    }

    @Override
    public void showTaskCommentList(List<TaskCommentDto> result, int pageNum) {
        if (pageNum == 1) {
            mCommentList.clear();
        }
        mCommentList.addAll(result);
        mCommentAdapter.notifyDataSetChanged();
        onLoad(result.size());
    }

    @Override
    public void acceptTaskSuccess() {
        mDetailsDto.setStatus(0);
        mBtnCancel.setVisibility(View.VISIBLE);
        tvOverTime.setVisibility(View.GONE);
        tvHandle.setText("去提交");
        showToast("接任务成功，在活动结束前完成任务");
    }

    @Override
    public void cancelTaskSuccess() {
        showToast("取消成功");
        presenter.loadTaskDetail(missionId);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == 1005) {
            pageNum = 1;
            presenter.loadComment(missionId, pageNum);
        }
    }

    public void onLoad(int size) {
        if (mRefLayout == null) {
            return;
        }
        mRefLayout.finishRefreshLoadingMore();
        if (size < 10) {
            mRefLayout.enableLoadMore(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMyTime != null) {
            mMyTime.cancel();
            mMyTime = null;
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    private PlatActionListener mPlatActionListener = new PlatActionListener() {
        @Override
        public void onComplete(Platform platform, int action, HashMap<String, Object> data) {
            if (handler != null) {
                if (platform.getName().equals(Wechat.Name) || platform.getName().equals(WechatMoments.Name))
                    return;
                Message message = handler.obtainMessage();
                message.obj = "分享成功";
                handler.sendMessage(message);
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享失败";
                handler.sendMessage(message);
            }
        }

        @Override
        public void onCancel(Platform platform, int action) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享取消";
                handler.sendMessage(message);
            }
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String toastMsg = (String) msg.obj;
//            showToast(toastMsg);
        }
    };
}
